package net.lovesrc.allin.biz.gogohome;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhouzhou.fastjava.BizException;
import com.zhouzhou.fastjava.http.Requests;
import com.zhouzhou.fastjava.util.ThreadKit;
import net.lovesrc.allin.biz.BaseService;
import net.lovesrc.allin.utils.MyRandomUtils;
import net.lovesrc.support.service.mobileverifycode.MobileVerifyCodeService;
import net.lovesrc.support.service.mobileverifycode.MobileVerifyCodeWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

@Component
@EnableScheduling
public class GogoHomeLoginSign extends BaseService {

    public AtomicBoolean flag = new AtomicBoolean(true);
    public AtomicBoolean flagLogin = new AtomicBoolean(true);

    public static final ExecutorService qianDaoExecutorPools = Executors.newFixedThreadPool(512);

    public void sign(JSONObject phone) {
        String token = login(phone);
        for (int i = 0; i <100 ; i++) {
            qianDaoExecutorPools.submit(()-> qingdao(token, phone));
        }
        ThreadKit.sleepSeconds(5);
        after(token, phone);
    }


    public void mgtConvert(String phone, long number) {
        List<Map<String,Object>> mgtUserInfos;
        try {
            int start = 0;
            int page = 100;
            while (!(mgtUserInfos = jdbcTemplate.queryForList("select * from MGT_USER_INFO where limit ?,?", start, start + page)).isEmpty() && flagLogin.get()) {
                mgtUserInfos.forEach(mgtUserInfo -> {
                    try {
                        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(mgtUserInfo));
                        String token = login(jsonObject);
                        String text = Requests.get("http://cr.dongweicom.com/api/extract/userMgtZ")
                                .contentType("application/json")
                                .param("cardnum", phone)
                                .param("money", number <= 0 ? jsonObject.getString("number") : number + "")
                                .param("extract_type", "bank")
                                .param("bankname", "请选择银行")
                                .header("Authori-zation", "Bearer " + token)
                                .execute().asText();
                        System.out.println(text);
                        jdbcTemplate.update("update MGT_USER_INFO  set `number` = 0  where username = ?", jsonObject.getString("username"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
                start += page;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void after(String token, JSONObject phone) {

        JSONObject s = Requests.get("http://cr.dongweicom.com/api/user")
                .contentType("application/json")
                .header("Authori-zation", "Bearer " + token)
                .execute().asJson();

        Map<String, Object> username = jdbcTemplate.queryForMap("select * from MGT_USER_INFO where username = ?", phone.getString("username"));

        if (username != null && !username.isEmpty()) {
            jdbcTemplate.update("update MGT_USER_INFO  set `number` = ? ,invitationCode =?, signTime = ? where username = ?", (long)Double.parseDouble(s.getJSONObject("data").getString("integral")), s.getJSONObject("data").getString("uid"), LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), phone.getString("username"));
        }
    }

    private void qingdao(String token, JSONObject phone) {

        String s = Requests.post("http://cr.dongweicom.com/api/sign/integral")
                .contentType("application/json")
                .header("Authori-zation", "Bearer " + token)
                .execute().asText();
        System.out.println(s);
    }

    private String login(JSONObject phone) {
        JSONObject jsonObject = Requests.post("http://cr.dongweicom.com/api/login")
                .contentType("application/json")
                .param("account", phone.getString("username"))
                .param("password", phone.getString("password"))
                .execute().asJson();
        if (jsonObject == null || jsonObject.getJSONObject("data") == null || jsonObject.getJSONObject("data").getString("token") == null) {
//            jdbcTemplate.update("delete from MGT_USER_INFO where username = ?", phone.getString("username"));
            throw BizException.messageOf("未注册的手机号，无法登陆");
        }
        return jsonObject.getJSONObject("data").getString("token");
    }



    @Scheduled(cron = "0 0 9 * * ?")
    public void login() {
        //查数据库 定时签到
        List<Map<String,Object>> mgtUserInfos;
        try {
            int start = 0;
            int page = 100;
            while (!(mgtUserInfos = jdbcTemplate.queryForList("select * from MGT_USER_INFO limit ?,?",start, start + page)).isEmpty() && flagLogin.get()) {
                mgtUserInfos.forEach(mgtUserInfo -> {
                    try {
                        TimeUnit.MILLISECONDS.sleep(100);
                        HomeAccountQueue.queue.put(JSON.parseObject(JSON.toJSONString(mgtUserInfo)));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
                start += page;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(5120);
        GogoHomeLoginSign gogoHomeLoginSign = new GogoHomeLoginSign();
        JSONObject jsonObject =new JSONObject();
        jsonObject.fluentPut("username","19528002013").fluentPut("password","mmm123456");
        String token = gogoHomeLoginSign.login(jsonObject);
        for (int i = 0; i <10000 ; i++) {
            service.submit(()-> gogoHomeLoginSign.qingdao(token,jsonObject ));
            System.out.println(Thread.currentThread().getName()+"正在进行...");
        }
    }

}
